class GetPostsByDate {
  
  Blog _blog;
  
  GetPostsByDate(Blog blog){
    _blog = blog;
  }

  void showWindow(){
  
  	// set "BY DATES" active on side bar
  	SideBar bar = _blog.getSideBar();
    bar.setActive(document.query('#filterByDates'));
  
    document.query('#GetByDatesWindow').innerHTML = Windows.getCalendar();
	//setting events
	document.query('#cancelGetByDates').on.click.add((events) => closeWindow());
    document.query('#getByDates').on.click.add((events) => postToWall());
  }
  
  void closeWindow(){
  	document.query('#GetByDatesWindow').innerHTML = '';
	SideBar bar = _blog.getSideBar();
    bar.revert();
  }
  
  String getStartDay(){
	var month = document.query('#startMonth');
  	var year = document.query('#startYear');
  	var day = document.query('#startDay');
  	
  	String syear = year.value;
	String smonth = month.value;
	if(smonth.length == 1)
		smonth = '0' + smonth;
		
  	String sday = day.value;
	if(sday.length == 1)
		sday = '0' + sday;
		
	String startDate = "$syear-$smonth-$sday 00:00:00.000";
	return startDate;
  }
  
  
  String getEndDay(){
  	var month = document.query('#endMonth');
  	var year = document.query('#endYear');
  	var day = document.query('#endDay');
  	
  	String eyear = year.value;
	String emonth = month.value;
	if(emonth.length == 1)
		emonth = '0' + emonth;
		
  	String eday = day.value;
	if(eday.length == 1)
		eday = '0' + eday;
		
	String endDate = "$eyear-$emonth-$eday 23:59:59.999";
	return endDate;
  }

  bool isValidDates(String startDate, String endDate){
		Date sDate = new Date.fromString(startDate);
		Date eDate = new Date.fromString(endDate);

		if(eDate.value >= sDate.value){
			return true;
		}
		return false;
  }
  
  void postToWall(){
  
	String startDate = getStartDay();
	//window.alert("startDate: $startDate");
	
	
	String endDate = getEndDay();
	//window.alert("endDate: $endDate");
	
	
	
	if(!isValidDates(startDate, endDate)){
		document.query('#errordates').innerHTML = 'Start date must be erlier than the last date!';
		return;
	}

	String url = _blog.getURL();
	document.query('#GetByDatesWindow').innerHTML = '';
	
	document.query('#pagename').innerHTML = 'Posts between ' + dateToString(startDate) +' and '+ dateToString(endDate);
	
	_blog.setPostRequester(new PostReqByDates(_blog,url,startDate,endDate));
	_blog.showPosts();
  }
  
  String dateToString(String sd){
    Date d = new Date.fromString(sd);
  	String str = '' + d.day + '-' + d.month + '-' + d.year;
  	return str;
  }
  
  
  
}// class
